package com.saver.core.processor.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import com.saver.core.util.Constantes;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class Util {
	
    private static SimpleDateFormat dateFormat = new SimpleDateFormat(
    		Constantes.FORMAT_DATE_SQLITE, Locale.getDefault());
    private static SimpleDateFormat dateFormatService = new SimpleDateFormat(
    		Constantes.FORMAT_DATE_SERVICE, Locale.getDefault());

	public static String getStringToDateTime(Date date) {
        return dateFormat.format(date);
	}
	
	public static Date getDateTimeToString (String date) {
        try {
			return dateFormat.parse(date);
		} catch (ParseException e) {
			Log.e(Util.class.getName(), "Error al convertir fecha", e);
			return null;
		}
	}
	
	public static String getServiceStringToDateTime(Date date) {
        return dateFormatService.format(date);
	}
	
	public static Date getServiceDateTimeToString (String date) {
        try {
			return dateFormatService.parse(date);
		} catch (ParseException e) {
			Log.e(Util.class.getName(), "Error al convertir fecha", e);
			return null;
		}
	}
	
	public static boolean esVacio (String str) {
		if (str == null || "".equals(str.trim())) {
			return true;
		}
		return false;
	}
	
	public static boolean noEsVacio (String str) {
		return !esVacio(str);
	}
	
	public static boolean tieneConexionInternet (Context context) {
		try {
		    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		    NetworkInfo netInfo = cm.getActiveNetworkInfo();
		    return netInfo != null && netInfo.isConnectedOrConnecting();
		    
		} catch (Exception ex) {
			return false;
		}
	}
	
	public static Integer getInteger (JSONObject jsonObject, String propiedad) throws JSONException {
		if (jsonObject.has(propiedad)) {
			String valor = jsonObject.getString(propiedad);
			if (valor == null || "null".equalsIgnoreCase(valor)) {
				return null;
				
			} else {
				return Integer.parseInt(valor);
			}
		}
		return null;
	}
	
	public static Short getShort (JSONObject jsonObject, String propiedad) throws JSONException {
		if (jsonObject.has(propiedad)) {
			String valor = jsonObject.getString(propiedad);
			if (valor == null || "null".equalsIgnoreCase(valor)) {
				return null;
				
			} else {
				return Short.parseShort(valor);
			}
		}
		return null;
	}
	
	public static String getString (JSONObject jsonObject, String propiedad) throws JSONException {
		if (jsonObject.has(propiedad)) {
			return jsonObject.getString(propiedad);
		}
		return null;
	}

}
